package com.stream.utils.validator;

import com.stream.utils.RRException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * Hibernate-validator 校验工具类
 * Created by yebaokang on 2017/5/26.
 */
public class ValidatorUtils {
    private static Validator validator;
    static{
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     * @param o 待校验对象
     * @param groups 待校验的组
     * @throws RRException 校验不通过，则报 RRException 异常
     */
    public static void validateEntity(Object o, Class<?>... groups) throws RRException {
        Set<ConstraintViolation<Object>> validate = validator.validate(o, groups);
        if (!(validate.isEmpty())) {
            ConstraintViolation<Object> constraints = validate.iterator().next();
            throw new RRException(constraints.getMessage());
        }
    }

}
